package com.translate.web.config.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.common.util.StringUtil;
import com.jwt.IJwtUtil;
import com.msg.ResponseCode;
import com.translate.web.annotation.JwtIgnore;
import com.translate.web.config.common.excecption.LoginError;
import com.translate.web.config.contract.IJwtExtend;


@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource(name="JwtExtend")
	private IJwtExtend jwtComponent;

	public static final String USER_KEY = "userId";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		// 忽略带JwtIgnore注解的请求, 不做后续token认证校验
		if (handler instanceof HandlerMethod) {

			HandlerMethod handlerMethod = (HandlerMethod) handler;

			JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);

			if (jwtIgnore != null) {
				return true;
			}
		}

		if (HttpMethod.OPTIONS.equals(request.getMethod())) {
			response.setStatus(HttpServletResponse.SC_OK);
			return true;
		}

		// 获取用户凭证
		String header = jwtComponent.getJwtConfig().getHeader();

		String token = null;

		if (StringUtil.isNotEmpty(header)) {
			token = request.getHeader(header);
		}

		if (StringUtil.isBlank(token)) {
			token = request.getParameter(header);
		}

		// 凭证为空
		if (StringUtil.isBlank(token)) {
			throw new LoginError(ResponseCode.ERROR_LOGIN_NONE_TOKEN);
		}

		long userId = jwtComponent.getId(token);
		if (0 == userId) {
			throw new LoginError(ResponseCode.ERROR_LOGIN_FAILURE);
		} 
		// 设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute(USER_KEY, userId);
		
		request.setAttribute("userName", this.jwtComponent.getUserNameFromToken(token));
		
		request.setAttribute("realname", this.jwtComponent.getRealname(token));

		request.setAttribute("mobile", this.jwtComponent.getMobile(token));
		
		return true;
	}
}